from socket import *
from multiprocessing import Process


def handler(clientSocket):
	"""处理客户端请求"""
	# 获取客户端请求数据
	requestData = clientSocket.recv(1024)
	print(requestData)
	# 构造响应数据
	responseStartLine = "HTTP/1.1 200 OK\r\n"
	responseHeaders = "Server: My Server\r\n"
	responseBody = "hello world!"
	response = responseStartLine + responseHeaders + "\r\n" + responseBody
	print(response)
	# 向客户端返回响应数据
	clientSocket.send(bytes(response, 'utf-8'))
	# 关闭客户端
	clientSocket.close()


if __name__ == '__main__':
	serverSocket = socket(AF_INET, SOCK_STREAM)
	serverSocket.bind(('', 8080))
	serverSocket.listen(128)

while True:
	clientSocket, clientAddress = serverSocket.accept()
	print("[%s, %s] 用户连接上了" % clientAddress)
	# 拷贝了一份到子进程中去了
	handleClientProcess = Process(target=handler, args=(clientSocket,))
	handleClientProcess.start()
	clientSocket.close()
